from machine import Pin
from mqtt import Mqtt
from cfg import Config
import utils
import time, gc


class Todo:
    def __init__(self):
        self.mqtt = Mqtt()

        self.mqtt.set_on_message(self._on_message)
        self.mqtt.set_on_check_message(self._on_check_message)
        self.mqtt.set_on_keep_connect(self._on_keep_connect)

        self.locked = 0
        self.low_count = 0
        self.sensor_value = 0
        self.light_state = 0

        # ---- GPIO ----
        # GPIO00 not all
        # GPIO01 not
        # GPIO02 board led
        # GPIO03 not
        # GPIO04 ok
        # GPIO05 ok
        # GPIO09 not  always reboot
        # GPIO10 ok  power must be right
        # GPIO12 ok
        # GPIO13 ok
        # GPIO14 ok
        # GPIO15 not all
        # GPIO16 board led flash
        self.sensor = Pin(12, Pin.IN)

    def _on_message(self, mqtt, topic, msg):
        if msg == b'on':
            import wakeup
            wakeup.send()

        gc.collect()

    def _on_check_message(self, mqtt, timer):
        if self.locked == 0 and self.sensor.value() == 1:
            self.locked = 1
            self.mqtt.publish(Config.ON)
            utils.flash_board_led()
            print("来了，老弟！！！")

        gc.collect()

    def _on_keep_connect(self, mqtt, timer):
        self.locked = 0
        if self.sensor.value() == 0:
            self.mqtt.publish(Config.OFF)
        gc.collect()

    def run(self):
        self.mqtt.start()


if __name__ == "__main__":
    pass
